﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using Luna;

namespace TextDataExtractor.DEML {
	public class SetDataAction : AbstractAction {

		public override void execute(ExecutionContext context) {
			base.execute(context);
			if (Operation.Equals("set", StringComparison.OrdinalIgnoreCase))
				setOperation(context);
			else if (Operation.Equals("append", StringComparison.OrdinalIgnoreCase))
				appendOperation(context);

		}

		private void appendOperation(ExecutionContext context) {
			string template = getArgument("value");
			string indexer = null;
			string name = getArgument("name");
			if (!name.StartsWith("$"))
				name = "$" + name;
			IDataProvider storage = resolveVariableName(context, name, out indexer);
			object value = formatValue(context, template);
			if (storage is IDataStorage && indexer.isNotNullAndEmpty()) {
				object list = storage.getDataItem(indexer);
				if (list == null)
					(storage as IDataStorage).setDataItem(indexer, list = new List<object>());
				(list as IList<object>).Add(value);
			}

			//string s = string.Format("append: {0} <- {1}", name, value);
			//Debug.WriteLine(s);
		}

		private void setOperation(ExecutionContext context) {
			string template = getArgument("value");
			string indexer = null;
			string name = getArgument("name");
			if (!name.StartsWith("$"))
				name = "$" + name;
			IDataProvider storage = resolveVariableName(context, name, out indexer);
			object value = formatValue(context, template);
			if (storage is IDataStorage)
				(storage as IDataStorage).setDataItem(indexer, value);

			//string s = string.Format("set: {0} <- {1}", name, value);
			//Debug.WriteLine(s);
		}
	}
}
